<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\shop\Order;
use app\admin\model\shop\OrderRefund;
use app\admin\model\User;
use app\api\model\IncubatorOrder;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{

    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);

        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $incubator_num_list = Db("incubator_order")
            ->where('pay_status',1)
            ->where('pay_time', 'between time', [$starttime, $endtime])
            ->field('pay_time, SUM(num) AS nums, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        $incubatornumlist = array_fill_keys($column, 0);
        foreach ($incubator_num_list as $k => $v) {
            $incubatornumlist[$v['join_date']] = $v['nums'];
        }

        $incubator_money_list = Db("incubator_order")
            ->where('pay_status',1)
            ->where('pay_time', 'between time', [$starttime, $endtime])
            ->field('pay_time, SUM(price) AS nums, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        $incubatormoneylist = array_fill_keys($column, 0);
        foreach ($incubator_money_list as $k => $v) {
            $incubatormoneylist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $addonList = get_addon_list();
        $totalworkingaddon = 0;
        $totaladdon = count($addonList);
        foreach ($addonList as $index => $item) {
            if ($item['state']) {
                $totalworkingaddon += 1;
            }
        }
        $tomorrow_start = date('Y-m-d', strtotime("+1 day"));
        $this->view->assign([
            'todayincubatornum' => IncubatorOrder::where('pay_status',1)->whereTime('pay_time', 'today')->sum('num'),
            'sevenincubatornum' => IncubatorOrder::where('pay_status',1)->whereTime('pay_time', '-7 days')->sum('num'),
            'thirtyincubatornum' => IncubatorOrder::where('pay_status',1)->whereTime('pay_time', '-30 days')->sum('num'),
            'totalincubatornum' => IncubatorOrder::where('pay_status',1)->sum('num'),
            'tomorrowRefundNum' => OrderRefund::where('o.date', '=', $tomorrow_start)
                ->alias('r')
                ->join('__SHOP_ORDER__ o', 'r.order_id = o.id')
                ->where('r.status', 1)->count(),

            'todayincubatorprice' => IncubatorOrder::where('pay_status',1)->whereTime('pay_time', 'today')->sum('price'),
            'sevenincubatorprice' => IncubatorOrder::where('pay_status',1)->whereTime('pay_time', '-7 days')->sum('price'),
            'thirtyincubatorprice' => IncubatorOrder::where('pay_status',1)->whereTime('pay_time', '-30 days')->sum('price'),
            'totalincubatorprice' => IncubatorOrder::where('pay_status',1)->sum('price'),

            'todayorderprice' => Order::where('paystate',1)->whereTime('paytime', 'today')->sum('payamount'),
            'sevenorderprice' => Order::where('paystate',1)->whereTime('paytime', '-7 days')->sum('payamount'),
            'thirtyorderprice' => Order::where('paystate',1)->whereTime('paytime', '-30 days')->sum('payamount'),
            'totalorderprice' => Order::where('paystate',1)->sum('payamount'),

            'totaluser'         => User::count(),
            'totaladdon'        => $totaladdon,
            'totaladmin'        => Admin::count(),
            'totalcategory'     => \app\common\model\Category::count(),
            'todayusersignup'   => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'    => User::whereTime('logintime', 'today')->count(),
            'sevendau'          => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'         => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'          => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'          => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'       => count($dbTableList),
            'dbsize'            => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'totalworkingaddon' => $totalworkingaddon,
            'attachmentnums'    => Attachment::count(),
            'attachmentsize'    => Attachment::sum('filesize'),
            'picturenums'       => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'       => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        $this->assignconfig('incubatornum', array_values($incubatornumlist));
        $this->assignconfig('incubatormoney', array_values($incubatormoneylist));

        return $this->view->fetch();
    }

}
